package com.twd.allcomponent.login.utils;

import com.twd.allcomponent.login.bean.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * @author lixiang
 * @since 2022-01-13
 */
@Slf4j
public class JWTUtil {

    /**
     * token过期时间，正常是7天
     */
    private static final long EXPIRE = 1000L * 60 * 60 * 24 * 7;

    /**
     * 加密的密钥
     */
    private static final String SECRET = "d8de020f63754a9fa746ea74b831afc3sjksaksafjkaskfassfsfsdfsdfsdfsdfsdfsdfsd";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "LONGIN-TEST";

    /**
     * subject 颁布地址
     */
    private static final String SUBJECT = "lixiang";

    /**
     * 根据用户信息生成token
     * @param user
     * @return
     */
    public static Map<String,Object> geneJsonWebToken(User user){

        if(user == null){
            throw new NullPointerException("loginUser对象为空");
        }

        Date endDate = new Date(System.currentTimeMillis() + EXPIRE);

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("age", user.getAge())
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("phone", user.getPhone())
                .claim("sex", user.getSex())
                .setIssuedAt(new Date())
                .setExpiration(endDate)
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();

        token = TOKEN_PREFIX+token;

        Map<String,Object> map = new HashMap<>();
        map.put("accessToken",token);
        map.put("accessTokenExpires",endDate);

        return map;
    }

    /**
     * 检验token方法
     * @param token
     * @return
     */
    public static Claims checkJWT(String token){

        try{
            return Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
        }catch (Exception e){
            log.info("JWT token解密失败");
            return null;
        }
    }

        public static void main(String[] args) {
            User user = User.builder()
                    .age(18)
                    .id(1L)
                    .name("李祥")
                    .phone("13820934720")
                    .sex(1)
                    .username("lixiang")
                    .build();

            Map<String, Object> objectMap = JWTUtil.geneJsonWebToken(user);

            System.out.println("LoginUser加密：");
            objectMap.forEach((k,v)->{
                System.out.println("---key:"+k+",value:"+v);
            });

            String accessToken = String.valueOf(objectMap.get("accessToken"));
            System.out.println("Token解密：");
            Claims claims = JWTUtil.checkJWT(accessToken);
            System.out.println("---name:"+claims.get("name"));
            System.out.println("---age:"+claims.get("age"));
            System.out.println("---phone:"+claims.get("phone"));
            System.out.println("---username:"+claims.get("username"));
            System.out.println("---sex:"+claims.get("sex"));
        }

}
